package com.bbx.demo.broadcast;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@ChannelHandler.Sharable
public class BroadcastServerHandler extends ChannelInboundHandlerAdapter {

    private static ChannelGroup channerGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Channel channel = ctx.channel();
        String msg1 = (String) msg;
        log.info("msg1[{}]", msg1);
        channerGroup.forEach(ch ->{
            if (ch.equals(channel)) {
                ctx.writeAndFlush("[自己]===>发送的消息："+msg1);
            } else {
                ch.writeAndFlush("[" + channel.remoteAddress() + "]===>发送的消息：" + msg1);
            }
        } );

    }


    /**
     * channel 建立连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channerGroup.writeAndFlush("[服务端]===>" + channel.remoteAddress() + "上线了");
        channerGroup.add(channel);

    }

    /**
     * channel   关闭连接
     * @param ctx
     * @throws Exception
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channerGroup.writeAndFlush("[服务端]===>" + channel.remoteAddress() + "下线了");
        //不需要调用 channerGroup.remove(),因为 channerGroup存放的是存活的channel ，断开连接的会自动移除
    }
}
